#!/usr/bin/env node

const http=require('http'),
      url = require('url'),
      qs = require('querystring');
let items = [];

function genPage(){
  let html=`
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>登陆页面</title>
  </head><lable>密码:</lable>
    <input type="password" name='password'>
    <br>  
  <body>
  <h1>Todo List</h1>
  <form method='GET' action="http://192.168.152.144:8080">
    
    <input type="text" name='item'>                             
    <input type="submit" value='submit'>
    
  </form>
  <ul id='items'>
    ${items.map(i => '<li>' + i + '</li>').join('\n')}
  </ul>
  </body>
  </html>`;

  return html;
}
http.createServer((req,res)=>{
  //status code       
  //header,txt/html
  let addr = url.parse(req.url);
  if(addr.pathname!=='/'){
    res.statusCode=404;
    res.setHeader('content-type','text/html');
    res.end('<h1>Not found</h1>');
    return;
  }

  let item = qs.parse(addr.query).item;
  if(item !== '' && typeof item !== 'undefined') items.push(item);
  res.writeHead(200,{
    'content-type':'text/html',
    'content-length':Buffer.byteLength(genPage())
  });
  // res.statusCode = 200;
  // res.setHeader('Content-type','text/html')
  // res.setHeader('Content-length',Buffer.byteLength(html));//求html的字节长度
  // 完成响应数据的封装
  res.end(genPage());
}).listen(8080);
